<?php
/**
* Joomla Community Builder User Plugin: plug_cbgooglemap
* @version $Id$
* @package plug_cbgooglemap
* @subpackage cbgooglemap.php
* @author Nikolai Plath
* @copyright (C)
* @license Limited  http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @alpha
*/

/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

class getGoogleMapTab extends cbTabHandler
{

	function getGoogleMapTab()
	{
		$this->cbTabHandler();
	}
	function getEditTab($tab,$user,$ui)
	{
		//echo '<h3>Please edit gMap from Display until i find out how to use the EditTab...</h3>';
	}	
	function getDisplayTab($tab,$user,$ui)
	{
		global $my;
		global $database;
		global $mainframe;
		$OWNER = false;
		if ( $my->id == $user->id )
		{
			$OWNER = true;
		}
		//echo $OWNER.$my->id. $user->id;
		$return = null;
		$params = $this->params; // get parameters (plugin and related tab)
		
		$is_helloworld_plug_enabled = $params->get('hwPlugEnabled', "1");
		$helloworld_tab_message = $params->get('hwTabMessage', "Hello Joomlapolitans!");
		if ($is_helloworld_plug_enabled != "0")
		{
			if($tab->description != null)
			{
				$return .= "\t\t<div class=\"tab_Description\">"
					. $tab->description	// html content is allowed in descriptions
					. "</div>\n";
			}
			$return .= "\t\t<div>\n"
				. "<p>"
				. htmlspecialchars($helloworld_tab_message) // make all other output html-safe
				. "</p>
				</div>";

			if ($_GET['gmapmessage'] == 'OK')
			{
				echo '<h3>Changes have been saved</h3>';
			}
	if ($_POST['gmapcoords'] != '')
	{
		if ( $OWNER )
		{
			$ttemp = substr($_POST['gmapcoords'],1,strlen($_POST['gmapcoords'] )-2);
			$ttemp = explode (",", $ttemp);
			$query = "UPDATE #__comprofiler"
			. "\n SET cb_googlemaplat = " . $ttemp[0] .", "
			. "\n cb_googlemaplng = " . $ttemp[1]
			. "\n WHERE id = " . $user->id;
			$database->setQuery( $query );
			if ( $database->query() )
			{
				mosRedirect ( 'index.php?option=com_comprofiler&amp;Itemid='.$Itemid.'&amp;gmapmessage=OK' );
			} else
			{
				echo "<h1>There was an ERROR</h1>";
			}
		}
	}
	
		$Map_Width = $params->get('width',"800px");
		$Map_Height = $params->get('height',"400px");
		$GMapKey = $params->get('google_apikey',"NOKEY");

		$Init_Lat = $params->get('center_lat',"18.979025953255267");//set
		$Init_Lng = $params->get('center_lng',"-15.46875");         //to
		$Init_Zoom = $params->get('zoom',"2");                      //world view
	
	$mainframe->addCustomHeadTag( "<script src=\"http://maps.google.com/maps?file=api&amp;v=2.76&amp;key=".$GMapKey."\" type=\"text/javascript\"></script>");

////////////// LANGUAGE ////////////////////////////////////////
	define ( '_TAB_EINS_TEXT', 'Contact' );//ins Langfile
	define ( '_TAB_ZWEI_TEXT', 'Infos' );//ins Langfile
	define ( '_TAB_WEBSITE', 'Infos' );//ins Langfile


	define ( 'CBGMAP_SUBMIT_TITEL', 'When you\'re done please press' );//ins Langfile
	define ( 'CBGMAP_SUBMIT_BTN_SUBMIT', 'Update' );//ins Langfile
/*
	define ( '_', '' );//ins Langfile
	define ( '_', '' );//ins Langfile
	define ( '_', '' );//ins Langfile
	define ( '_', '' );//ins Langfile
	define ( '_', '' );//ins Langfile
	define ( '_', '' );//ins Langfile
	define ( '_', '' );//ins Langfile
	define ( '_', '' );//ins Langfile
	define ( '_', '' );//ins Langfile
	define ( '_', '' );//ins Langfile
*/
	
////////////////////////////////////////////////////////////////

//Prepare Tabs for Markers
//The CB Userpic
	$cbPicPath = 'components/com_comprofiler/images/';
	if (strpos($user->avatar, "/") === false )
	{
		$cbPicPath='images/comprofiler/tn';
	} else
	{	
		$cbPicPath = 'components/com_comprofiler/images/';
	}
	
	if ($user->avatar == '')
	{
		$TabEinsContent = "<strong>" . $user->firstname . " " . $user->lastname . "</strong>";
	} else
	{
		$TabEinsContent = "<img src='".$cbPicPath.$user->avatar."' alt='Image' /><br /><strong>"
		.$user->firstname." ".$user->lastname
		."</strong>";
	}
	$LinkString = $user->cb_website;
	$ttemp = explode ("|*|", $user->cb_website);

	$TabZweiContent = "<strong>" . _TAB_WEBSITE . ":</strong><br /><a href='http://".$ttemp[0]."' target='_blank'>".$ttemp[1]."</a>";
	$TabString = "var infoTabs = [
	  new GInfoWindowTab(\""._TAB_EINS_TEXT."\", \"".$TabEinsContent."\"),
	  new GInfoWindowTab(\""._TAB_ZWEI_TEXT."\", \"".$TabZweiContent."\")
	];";

// we have a location
if ( $user->cb_googlemaplat )
{

$FullEditString ='';
$FullEditString .= $TabString;

$FullEditString .= "var posn = new GLatLng(".$user->cb_googlemaplat.", ".$user->cb_googlemaplng.");";

if ( $OWNER )
{
	$FullEditString .= '
	var marker = new GMarker(posn,  {draggable: true});';
} else {
	$FullEditString .= '
	var marker = new GMarker(posn);';
}

$FullEditString .= '
GEvent.addListener(marker, "click", function() {
  marker.openInfoWindowTabsHtml(infoTabs);
});

GEvent.addListener(marker, "dragstart", function() {
	map.closeInfoWindow();
});

GEvent.addListener(marker, "dragend", function() {
	document.getElementById("message2").value = marker.getPoint();
});

map.addOverlay(marker);';

$MarkerString = $FullEditString;

} else
{

///// NEW USER ///////////////////
//when clicked - add a new marker
if ( $OWNER )
{

$MapEditString .= '
	var clicked;
	GEvent.addListener(map, "click", function(marker, point)
	{
		if (marker)
		{
  		} else
		{
			if (clicked != 1)
			{
				clicked=1;
			  	var marker = new GMarker(point, {draggable: true});
			    map.addOverlay(marker);

				document.getElementById("message2").value = point.toString();
	
				GEvent.addListener(marker, "dragend", function()
				{
				document.getElementById("message2").value = marker.getPoint();
				});
			}
		}			
});';
}
$MarkerString = $MapEditString;
}
//Prepare Tabs for Markers ENDE
//////////////////////////////////////////


//The submitform
$fromwhere = 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER['REQUEST_URI'];
$SendForm = '
<h3>' . CBGMAP_SUBMIT_TITEL . '</h3>
<form id="form1" name="form1" method="post" action="'. $fromwhere .'">
  <input name="gmapcoords" type="hidden" id="message2" size="40" value="" />
  <input type="submit" name="Submit" value="' . CBGMAP_SUBMIT_BTN_SUBMIT . '" id="btn_gmapsubmit" />
</form>
</p>';

	$repl = '';

	if ($OWNER)
	{
	$repl .= $SendForm;
	}


	// The Searchbox
	$repl .= '<h3>Try the search</h3>Location:';

	$repl .= '<form onsubmit="showAddress(); return false">
      <input id="search" size="60" type="text" value="">
      <input type="submit" value="Go!">
      <!--<input type="button" onclick="javascript:tst.clearOverlays();return false" value="Clear markers">-->
    </form>';
////The Message///
	$repl .= '<div id="message"></div>';


/////////////////////// The Map "Window"  //////////////////////////////
		$repl .= '<div id="gmap" style="width: ' . $Map_Width . '100%; height: ' . $Map_Height . '"></div>';
	/////////////////////////////////////////////////////////////////////
	
/////////////////////////////////////////////////////////////////////////////
/////////////// LET'S GO FIND SOME TROUBLE::: ////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
	
	// me make the map ...
	$repl .= "<script type='text/javascript'>//<![CDATA[\n";
	
			// global var linked to div
	$repl .="var tst=document.getElementById('gmap');
				 var tstint;
				 ";

	// Functions to wacth if the map has changed
	$repl .= "function checkMap()
		{
			if (GBrowserIsCompatible())
			{
				if (tst)
					if (tst.offsetWidth != tst.getAttribute(\"oldValue\"))
					{
						tst.setAttribute(\"oldValue\",tst.offsetWidth);

						if (tst.getAttribute(\"refreshMap\")==0)
						if (tst.offsetWidth > 0) {
							clearInterval(tstint);
							getMap();
							tst.setAttribute(\"refreshMap\", 1);
						} //if
					} //if
			} //if
		} //function checkMap\n";

$repl .="			if (tst.offsetWidth > 0) {
			var map = new GMap2(document.getElementById('gmap'));
			";

			// Function for displaying the map and marker
	$repl .= "function getMap()
		{";

	//the controls
	$repl .= "
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GOverviewMapControl());
	map.addControl(new GScaleControl());\n";

	//set the center
	if ( $user->cb_googlemaplat )
	{	//Set the center to known location
		$repl .= "map.setCenter(new GLatLng(".$user->cb_googlemaplat.", ".$user->cb_googlemaplng."), 12);";
	} else {   //Set the center to "world view"
		$repl .= "map.setCenter(new GLatLng(" . $Init_Lat . ", " . $Init_Lng . "), " . $Init_Zoom . ");";
	}//if

	$repl .= $MarkerString;
	 
 
	 //CONCLUSION !!!
	$repl .= '}//if (tst.offsetWidth > 0)
		}//function';
/*	  //]]></script>';*/
/////////// THE GEO CODER ///////////
$GeoCoder = "";//<script type=\"text/javascript\">//<![CDATA[\n";

$GeoCoder .= '// ====== Create a Client Geocoder ======

      var geo = new GClientGeocoder(); 
	  //var map = new GMap2(document.getElementById("gmap"));
	//var xxx = new GMap2(document.getElementById("gmap"));
      // ====== Array for decoding the failure codes ======
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      
      // ====== Geocoding ======
      function showAddress() {
        var search = document.getElementById("search").value;
        // ====== Perform the Geocoding ======        
        geo.getLocations(search, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
              document.getElementById("message").innerHTML = "Found " +result.Placemark.length +" results";
              // Loop through the results, placing markers
              for (var i=0; i<result.Placemark.length; i++) {
                var p = result.Placemark[i].Point.coordinates;
                var marker = new GMarker(new GLatLng(p[1],p[0]));
				//var xxLat = marker.getPoint().Lat();
				//var xxLon = marker.getPoint().Lon();
                document.getElementById("message").innerHTML += "<br />"+(i+1)+": "+ result.Placemark[i].address + marker.getPoint();
				//+"<a href=\'#\' onclick=\'map.setCenter(new GLatLng(p[1], p[0]),14);\'>Center</a>";
                //map.addOverlay(marker);
              }
              // centre the map on the first result
              var p = result.Placemark[0].Point.coordinates;
              map.setCenter(new GLatLng(p[1],p[0]),14);
			  //map.setCenter(new GLatLng(18.979025953255267, -15.46875), 2);
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              alert("Could not find " + search + " " + reason);
            }
          }
        );
      }
    
   ';
$GeoCoder .= " //]]></script>";
	 
  /////////////////////////////////GEOCODER END

	$repl .= $GeoCoder;



////Here comes the mysterious Timeoutcode for FCKNG IE #*+-
		// Call the Maps through timeout to render in IE also
		// Set an event for watching the changing of the map so it can refresh itself
	
	$repl .= "<script type=\"text/javascript\">//<![CDATA[\n";
			
	$repl .="if (GBrowserIsCompatible()) {
				tst.setAttribute(\"oldValue\",0);
				tst.setAttribute(\"refreshMap\",0);
				tstint=setInterval(\"checkMap()\",500);
			}
		//]]></script>
		";



	$return .= $repl;


		}
		return $return;
	} // end or getDisplayTab function
} // end of gethelloworldTab class
?>